(function(module){
	//初始化树布局
	$.tree.initView('resource-tree-view');
	//树的menu菜单id
	var menuId=$.parseHrefParam('menuId');
	//窗口变化时执行的方法
	$.resize.push({module:menuId, method: $.tree.initView, args: 'resource-tree-view'});
	//资源树对象
	module[menuId]={
		loadTree:	function(name, spreadId){
			var search={};
			if(name){
				search.name=name;
			}
			if(spreadId){
				search.spreadId=spreadId;
			}
			$.post('/system/systemResource/findTreeList', search, function(data){
				$.tree.loadTree('resource-tree', data, function(node){
					module[menuId].currNode=node;
					var id=node.data.id;
					module[menuId].toolbarShow('treeNodeClient', id);
					module[menuId].resourceView(id);
				});
				if(spreadId){
					module[menuId].toolbarShow('treeNodeClient', spreadId);
					module[menuId].resourceView(spreadId);
				}
			}, 'json');
		},
		treeSearch: function(search, event){
			if(event.keyCode==13){
				module[menuId].loadTree(search.value);
			}
		},
		toolbarShow: function(event, nodeId){
			var buttons=$("#resource-tree-view .unswift-tree-toolbar .layui-btn");
			if(event=='treeNodeClient'){
				var button, type;
				buttons.each(function(){
					button=$(this);
					type=button.attr("type");
					if(nodeId==-1){
						if(type=='submit' || type=='addBrother' || type=='delete'){
							if(!button.hasClass("layui-btn-disabled")){
								button.addClass("layui-btn-disabled");
							}
						}else if(button.hasClass("layui-btn-disabled")){
							button.removeClass("layui-btn-disabled");
						}
					}else if(button.hasClass("layui-btn-disabled")){
						button.removeClass("layui-btn-disabled");
					}
				});
			}else if(event=='addNext' || event=='addBrother'){
				buttons.each(function(){
					button=$(this);
					type=button.attr("type");
					if(type=='addNext' || type=='addBrother' || type=='delete'){
						if(!button.hasClass("layui-btn-disabled")){
							button.addClass("layui-btn-disabled");
						}
					}else if(button.hasClass("layui-btn-disabled")){
						button.removeClass("layui-btn-disabled");
					}
				});
			}
		},
		export: function(){
			var searchValue=$("#resource-tree-view [name='tree-search']").val();
			var data={};
			if(searchValue){
				data.name=searchValue;
			}
			$.module.export.handle(
				'部门导出', 
				'/imexport/systemResource/export', 
				data, 
				'/imexport/systemResource/export/stop'
			);
		},
		resourceView: function(id){
			$.get('/pages/admin/system/resource/resourceView.html',function(html){
				var body=$("#resource-tree-body");
				body.html(html);
				$("#resourceViewForm [create='false']").show();
				$.auth.init(body);
				$.dictionary.loadSelect('resourceViewForm', 'resourceType', 'resourceType');
				$.loadFormAjax('#resourceViewForm', 'POST', '/system/systemResource/view', $.toJson({id: id}), function(data, form){
					$.dictionary.loadRadioIcon('resourceViewForm', 'resourceIcon', 'icon', 'icon', data?data.icon:null);
					var type=data && data.type=='auth'?'rauth':data?data.type:'platform';
					form.find("["+type+"='false']").hide();
					if(id==-1){
						form.find("[rootedit='false']").attr("disabled", true);
					}else{
						form.find("[rootedit='false']").removeAttr("disabled");
					}
					form.find("[update='disabled']").attr("disabled", true);
					$.form.on('select(resourceType)', module[menuId].changeResourceType);
					$.form.render(null, 'resourceViewForm');
					if(data && (data.type=='menu' || data.type=='auth')){
						module[menuId].initParamName();
						var inputTableList=$("#resourceViewForm [lay-filter='inputTableList']");
						if(data.openInput && data.inputList && data.inputList.length>0){
							inputTableList.show();
							for(var i=0, length=data.inputList.length; i<length; i++){
								module[menuId].addInputRow(data.inputList[i]);
							}
						}
						$.form.on('switch(switchOpenInput)', function(data) {
							this.value=this.checked+'';
							if(this.checked){
								inputTableList.show();
							}else{
								inputTableList.hide();
							}
						});
						var outputTableList=$("#resourceViewForm [lay-filter='outputTableList']");
						if(data.openOutput && data.outputList && data.outputList.length>0){
							outputTableList.show();
							for(var i=0, length=data.outputList.length; i<length; i++){
								module[menuId].addOutputRow(data.outputList[i]);
							}
						}
						$.form.on('switch(switchOpenOutput)', function(data) {
							this.value=this.checked+'';
							if(this.checked){
								outputTableList.show();
							}else{
								outputTableList.hide();
							}
						});
					}
				});
			});
		},
		changeResourceType: function(select){
			var form=$("#resourceViewForm");
			form.find(".layui-form-item").show();
			form.find("["+(select.value=='auth'?'rauth':select.value)+"='false']").hide();
		},
		formRules:	{
			name	:	[{ required: true, message: "资源名称不能为空"}],
			authKey	:	[{ required: true, message: "权限key不能为空"}, { regexp: /[0-9a-zA-Z.]+/, message: "角色编码只能输入字母和数字"}],
			type	:	[{ required: true, message: "资源类型不能为空"}],
			icon	:	[{ required: true, message: "菜单图标不能为空"}],
			url		:	[{ required: true, message: "功能界面不能为空"}]
		},
		handleUpdate: function (){
			if(!$.valiForm('resourceViewForm', module.currModule.formRules)){
				return false;
			}
			var data=$.formToData('resourceViewForm');
			if(data.id){
				if(data.openInput=='true'){
					var inputList=[];
					var pass=module[menuId].getInputListData(inputList);
					if(!pass){
						return false;
					}
					data.inputList=inputList;
				}else{
					data.openInput='false';
				}
				if(data.openOutput=='true'){
					var outputList=[];
					var pass=module[menuId].getOutputListData(outputList);
					if(!pass){
						return false;
					}
					data.outputList=outputList;
				}else{
					data.openOutput='false';
				}
				$.post('/system/systemResource/update', data, function(res){
					$.success("操作成功");
					module[menuId].loadTree($("#resource-tree-view [name='tree-search']").val(), module[menuId].currNode.data.id);
				}, 'json');
			}else{
				$.post('/system/systemResource/create', data, function(res){
					$.success("操作成功");
					module[menuId].loadTree($("#resource-tree-view [name='tree-search']").val(), module[menuId].currNode.data.id);
				}, 'json');
			}
		},
		getInputListData: function(inputList){
			var rows=$("#resourceViewForm [lay-filter='inputTableList'] tbody tr:visible");
			if(rows.length==0){
				$.error("至少存在一个入参");
				return false;
			}
			var input, item, itemName, itemValue, itemTextName, itemTextValue;
			var pass=true;
			rows.each(function(index){
				input={};
				$(this).find("[list-name]").each(function(){
					item=$(this);
					itemName=item.attr('list-name');
					itemValue=item.val();
					if(itemValue){
						input[itemName]=itemValue;
					}
					itemTextName=item.attr('list-text');
					itemTextValue=item.find("option:selected").text()
					if(itemTextName && itemTextValue){
						input[itemTextName]=itemTextValue;
					}
					return true;
				});
				if(input.valueSource){
					inputList.push(input);
					return true;
				}else{
					$.error("入参列表的第"+(index+1)+"行“取值类型”不能为空");
					pass=false;
					return false;
				}
			});
			if(!pass){
				return false;
			}
			return true;
		},
		getOutputListData: function(outputList){
			var rows=$("#resourceViewForm [lay-filter='outputTableList'] tbody tr:visible");
			if(rows.length==0){
				$.error("至少存在一个出参");
				return false;
			}
			var output, item, itemName, itemValue, itemTextName, itemTextValue;
			var pass=true;
			rows.each(function(){
				output={};
				$(this).find("[list-name]").each(function(){
					item=$(this);
					itemName=item.attr('list-name');
					itemValue=item.val();
					if(itemValue){
						output[itemName]=itemValue;
					}
					itemTextName=item.attr('list-text');
					itemTextValue=item.find("option:selected").text()
					if(itemTextName && itemTextValue){
						output[itemTextName]=itemTextValue;
					}
					return true;
				});
				outputList.push(output);
				return true;
			});
			if(!pass){
				return false;
			}
			return true;
		},
		addChild: function(){
			$.post('/system/systemResource/view',{id:module[menuId].currNode.data.id}, function(data){
				var parentId=module[menuId].currNode.data.id;
				var form={
					parentId: parentId==-1?null:parentId,
					parentName: data?data.name:'',
					id: '',
					name:'',
					authKey: '',
					type: data && data.type=='platform'?'folder':(data && data.type=='folder'?'menu':data?'auth':'platform'),
					icon: '',
					url: '',
					sort: ''
				};
				$.loadFormData('#resourceViewForm', form, function(data, form){
					form.find("["+(data.type=='auth'?'rauth':data.type)+"='false']").hide();
					form.find("[create='false']").hide();
					form.find("[rootedit='false']").removeAttr("disabled");
					form.find("[update='disabled']").removeAttr("disabled");
					$("#resourceViewForm [lay-filter='inputTableList']").hide();
					$("#resourceViewForm [lay-filter='outputTableList']").hide();
					var type=$("#resourceViewForm [lay-filter='resourceType']").val();
					module[menuId].changeResourceType({value:type});
					//$("#resourceViewForm [create='false']").hide();
					module[menuId].toolbarShow('addNext', module[menuId].currNode.data.id);
					$.form.render(null, 'resourceViewForm');
				});
			}, 'json');
		},
		addBrother: function(){
			$.post('/system/systemResource/view',{id:module[menuId].currNode.data.id}, function(data){
				var form={
					id: '',
					name:'',
					authKey: '',
					type: data.type,
					icon: '',
					url: '',
					sort: ''
				};
				$.loadFormData('#resourceViewForm', form, function(data, form){
					form.find("["+(data.type=='auth'?'rauth':data.type)+"='false']").hide();
					form.find("[create='false']").hide();
					form.find("[rootedit='false']").removeAttr("disabled");
					form.find("[update='disabled']").removeAttr("disabled");
					$("#resourceViewForm [lay-filter='inputTableList']").hide();
					$("#resourceViewForm [lay-filter='outputTableList']").hide();
					module[menuId].changeResourceType({value:type});
					//$("#resourceViewForm [create='false']").hide();
					module[menuId].toolbarShow('addBrother', module[menuId].currNode.data.id);
					$.form.render(null, 'resourceViewForm');
				});
			}, 'json');
		},
		deleteThis: function(){
			$.layer.confirm("确定要删除此数据吗？", {btn:['确定','取消']}, function(){
				$.post('/system/systemResource/delete', {id:module[menuId].currNode.data.id}, function(){
					$.success("操作成功");
					module[menuId].loadTree($("#resource-tree-view [name='tree-search']").val());
				}, 'json');
			}, function(){
				
			});
		},
		initParamName: function(){
			var rowModel=$("#resourceViewForm [lay-filter='inputTableList'] [lay-filter='inputRowModel']");
			var valueSource=rowModel.find('[list-name="valueSource"]');
			var length=valueSource.children().length;
			if(length==0){
				var paramNameList=$.cache.loadAjax('system.config.findParamNameList', '/system/systemConfig/findParamNameList', 'POST', {module:'resource'}, 'dataList');
				if(paramNameList && paramNameList.length>0){
					valueSource.append("<option value=''>请选择</option>");
					for(var i=0, length=paramNameList.length; i<length; i++){
						valueSource.append("<option value='"+paramNameList[i].key+"'>"+paramNameList[i].value+"</option>");
					}
					var value=valueSource.val();
					var valueTd=rowModel.find('[list-td="valueTd"]');
					if(value){
						var paramName;
						for(var i=0, length=paramNameList.length; i<length; i++){
							if(paramNameList[i].key==value){
								paramName=paramNameList[i];
							}
						}
						if(paramName){
							if(paramName.valueType=='select'){
								var optionsData=paramName.optionsData;
								var html='<select list-name="value">';
								for(var i=0, length=optionsData.length; i<length; i++){
									html+="<option value='"+optionsData[i].key+"'>"+optionsData[i].value+"</option>"
								}
								html+='</select>';
								valueTd.html(html);
							}else if(paramName.valueType=='text'){
								valueTd.html('<input type="text" class="layui-input" list-name="value">');
							}
						}else{
							valueTd.html("");
						}
					}else{
						valueTd.html("");
					}
				}
			}
		},
		addInputRow: function(rowData){
			var authKey=$("#resourceViewForm [name='authKey']").val();
			var paramList=$.cache.loadAjax(authKey+".input", '/system/systemResource/findInputList', 'POST',{authKey: authKey}, 'dataList');
			if(paramList && paramList.length > 0){
				var rowModel=$("#resourceViewForm [lay-filter='inputTableList'] [lay-filter='inputRowModel']");
				var tbody=rowModel.parent();
				var row=rowModel.clone(true);
				row.show();
				row.removeAttr("lay-filter");
				var paramKeySelect=row.find('[list-name="paramKey"]');
				for(var j=0, length2=paramList.length; j<length2; j++){
					paramKeySelect.append("<option value='"+paramList[j].paramKey+"'>"+paramList[j].paramComment+"</option>");
				}
				if(rowData && rowData.id){
					row.find("[list-name='paramKey']").val(rowData.paramKey);
					valueSource=row.find("[list-name='valueSource']");
					valueSource.val(rowData.valueSource);
					var paramNameList=$.cache.loadAjax('system.config.findParamNameList', '/system/systemConfig/findParamNameList', 'POST', {module:'resource'}, 'dataList');
					if(paramNameList && paramNameList.length>0){
						var value=valueSource.val();
						var valueTd=row.find('[list-td="valueTd"]');
						if(value){
							var paramName;
							for(var i=0, length=paramNameList.length; i<length; i++){
								if(paramNameList[i].key==value){
									paramName=paramNameList[i];
								}
							}
							if(paramName){
								if(paramName.valueType=='select'){
									var optionsData=paramName.optionsData;
									var html='<select list-name="value">';
									for(var i=0, length=optionsData.length; i<length; i++){
										html+="<option value='"+optionsData[i].key+"'"+(rowData.value==optionsData[i].key?' checked':'')+">"+optionsData[i].value+"</option>"
									}
									html+='</select>';
									valueTd.html(html);
								}else if(paramName.valueType=='text'){
									valueTd.html('<input type="text" class="layui-input" list-name="value"'+(rowData.value?' value="'+rowData.value+'"':'')+'>');
								}
							}else{
								valueTd.html("");
							}
						}else{
							valueTd.html("");
						}
					}
				}
				tbody.append(row);
				$.form.render("select", 'resourceViewForm');
				$.form.on("select(valueSource)", module[menuId].changeValueSource);
			}
		},
		addAllInputRow: function(icon){
			var authKey=$("#resourceViewForm [name='authKey']").val();
			var paramList=$.cache.loadAjax(authKey+".input", '/system/systemResource/findInputList', 'POST',{authKey: authKey}, 'dataList');
			if(paramList && paramList.length > 0){
				var rowModel=$("#resourceViewForm [lay-filter='inputTableList'] [lay-filter='inputRowModel']");
				var tbody=rowModel.parent(), row, paramKeySelect;
				for(var i=0, length=paramList.length; i<length; i++){
					row=rowModel.clone(true);
					row.show();
					row.removeAttr("lay-filter");
					tbody.append(row);
					paramKeySelect=row.find('[list-name="paramKey"]');
					for(var j=0, length2=paramList.length; j<length2; j++){
						paramKeySelect.append("<option value='"+paramList[j].paramKey+"'"+(i==j?' selected':'')+">"+paramList[j].paramComment+"</option>");
					}
				}
				$.form.render("select", 'resourceViewForm');
				$.form.on("select(valueSource)", module[menuId].changeValueSource);
			}
		},
		deleteInputRow: function(icon){
			$(icon).parent().parent().remove();
		},
		changeValueSource: function(select){
			var row=$(select.elem).parent().parent();
			var valueTd=row.find('[list-td="valueTd"]');
			var value=select.value;
			if(value){
				var paramNameList=$.cache.loadAjax('system.config.findParamNameList', '/system/systemConfig/findParamNameList', 'POST', {module:'resource'}, 'dataList');
				var paramName;
				for(var i=0, length=paramNameList.length; i<length; i++){
					if(paramNameList[i].key==value){
						paramName=paramNameList[i];
					}
				}
				if(paramName){
					if(paramName.valueType=='select'){
						var optionsData=paramName.optionsData;
						var html='<select list-name="value">';
						for(var i=0, length=optionsData.length; i<length; i++){
							html+="<option value='"+optionsData[i].key+"'>"+optionsData[i].value+"</option>"
						}
						html+='</select>';
						valueTd.html(html);
					}else if(paramName.valueType=='text'){
						valueTd.html('<input type="text" class="layui-input" list-name="value">');
					}
				}else{
					valueTd.html("");
				}
			}else{
				valueTd.html("");
			}
			$.form.render(null, 'resourceViewForm');
		},
		addOutputRow: function(rowData){
			var authKey=$("#resourceViewForm [name='authKey']").val();
			var paramList=$.cache.loadAjax(authKey+".output", '/system/systemResource/findOutputList', 'POST',{authKey: authKey}, 'dataList');
			if(paramList && paramList.length > 0){
				var rowModel=$("#resourceViewForm [lay-filter='outputTableList'] [lay-filter='outputRowModel']");
				var tbody=rowModel.parent();
				var row=rowModel.clone(true);
				row.show();
				row.removeAttr("lay-filter");
				var paramKeySelect=row.find('[list-name="fieldName"]');
				for(var j=0, length2=paramList.length; j<length2; j++){
					paramKeySelect.append("<option value='"+paramList[j].paramKey+"'>"+paramList[j].paramComment+"</option>");
				}
				if(rowData && rowData.id){
					row.find("[list-name='fieldName']").val(rowData.fieldName);
				}
				tbody.append(row);
				$.form.render("select", 'resourceViewForm');
			}
		},
		addAllOutputRow: function(icon){
			var authKey=$("#resourceViewForm [name='authKey']").val();
			var paramList=$.cache.loadAjax(authKey+".output", '/system/systemResource/findOutputList', 'POST',{authKey: authKey}, 'dataList');
			if(paramList && paramList.length > 0){
				var rowModel=$("#resourceViewForm [lay-filter='outputTableList'] [lay-filter='outputRowModel']");
				var tbody=rowModel.parent(), row, paramKeySelect;
				for(var i=0, length=paramList.length; i<length; i++){
					row=rowModel.clone(true);
					row.show();
					row.removeAttr("lay-filter");
					tbody.append(row);
					paramKeySelect=row.find('[list-name="fieldName"]');
					for(var j=0, length2=paramList.length; j<length2; j++){
						paramKeySelect.append("<option value='"+paramList[j].paramKey+"'"+(i==j?' selected':'')+">"+paramList[j].paramComment+"</option>");
					}
				}
				$.form.render("select", 'resourceViewForm');
			}
		},
		deleteOutputRow: function(icon){
			$(icon).parent().parent().remove();
		}
	}
	module[menuId].loadTree();//初始化
	module.currModule=module[menuId];
})($.module);